//
//  VWPlayerSpeedControlLayer.swift
//  VideoWatcher
//
//  Created by JY_NEW on 2021/10/19.
//  Copyright © 2021 JunYue. All rights reserved.
//

import UIKit
import ijkPlayerManager

class VWPlayerSpeedControlLayer: VWPlayerSecondControlLayer {
    
    override var isFullScreenOnly: Bool {
        return true
    }
    
    override func loadPlayerManager(_ player: VideoPlayerManagerType) {
        super.loadPlayerManager(player)
        player.observer.rate.addTarget( self, action: #selector(self.onRateChanged))
    }
    override func unloadPlayerManager(_ player: VideoPlayerManagerType) {
        super.unloadPlayerManager(player)
        player.observer.rate.removeTarget(self)
    }
    
    @objc func onRateChanged() {
        if let idx = self.speeds.firstIndex(where: { ($0 + 0.001) > self.playerManager?.rate ?? 0}) {
            self.buttons.forEach({ $0.isSelected = false })
            self.buttons[idx].isSelected = true
        }
    }
    
    override func loadContainerView(_ containerView: UIView) {
        super.loadContainerView(containerView)
        
        for i in 0..<buttons.count {
            let button = buttons[i]
            button.set(.color(.init(rgb: 0xc6c6c6)), .color(.systemBlue, for: .highlighted), .color(.systemBlue, for: .selected), .font(.pingfang(bold: 16)), .event(self, #selector(self.onSpeed(_:))), .tag(i), .text(speedTitles[i]))
        }
        self.contentView.add {
            buttons.layout(first: .top(50), between: .bottomTop(30), .height, last: .bottom(50), all: .marginX)
        }
        
        self.onRateChanged()
    }
    
    let speeds:[Float] = [1, 1.25, 1.5, 2]
    let speedTitles:[String] = ["1.0X", "1.25X", "1.5X", "2.0X"]
    lazy var buttons = [UIButton(),UIButton(),UIButton(),UIButton()]
    
    @objc func onSpeed(_ sender: UIButton) {
        self.doAction { 
            self.playerManager?.rate = self.speeds[sender.tag]
        }
    }
}

